<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智搜</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        h2 {
            display: block;
            font-size: 2rex;
            margin-block-start: 0.83rex;
            margin-block-end: 0.83rex;
            margin-inline-start: 0px;
            margin-inline-end: 0px;
            font-weight: bold;
            unicode-bidi: isolate;
            font-family: "仿宋";
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #ffffff; /* 设置背景为白色 */
            height: 100vh;
            display: flex;
            flex-direction: column;
            margin: 0;
            overflow: hidden;
        }

        .header {
            text-align: center;
            padding: 0.6rex;
            font-size: 2.5rex;
            color: rgb(7, 7, 7);
            font-weight: bold;
            background-color: #cac9c9;
            border-radius: 0 0 0.6rex 0.6rex;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            height: 6vh; 
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: "仿宋";
        }

        .container {
            flex: 1;
            display: flex;
            flex-direction: column; /* 消息从上到下显示 */
            justify-content: flex-start; /* 消息从顶部开始 */
            padding: 20px;
            overflow-y: auto;
        }

        .chat-box {
            display: none;
            flex-direction: column;
            max-height: calc(100vh - 20vh); /* 减去header的高度和输入框的高度 */
            overflow-y: auto;
            padding: 15px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            justify-content: flex-start;  /* 确保消息从上到下排列 */
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }

        .chat-message {
            display: flex;
            align-items: flex-start;
            margin: 10px 0;
            padding: 0.5rex;
            border-radius: 10px;
            font-size: 16px;
            line-height: 1.5;
        }

        .chat-message.user {
            display: flex;
            flex-direction: row-reverse;
            background-color: #80deea;
            text-align: right; /* 使文本内容右对齐 */
            justify-content: flex-end;  /* 整个消息块右对齐 */
            border-radius: 12px 12px 0 12px;
            box-shadow: 0 4px 8px rgba(86, 158, 209, 0.4);
            margin-left: auto;  /* 让用户消息向右对齐 */
        }

        .chat-message.bot {
            background-color: #f1f1f1;
            border-radius: 2rex 2rex 2rex 0;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .chat-message img {
            width: 3rex;
            height:3rex;
            border-radius: 50%;
            margin: 0.8rex 0.8rex;
        }

        .message-text {
            word-wrap: break-word;
            font-size: 1.5rex;
            color: #333;
        }

        .input-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1.1rex;
            background-color: #ffffff;
            position: fixed;
            bottom: 0;
            width: 100%;
            box-sizing: border-box;
            border-top: 2px solid #ccc;
            border-radius: 10px 10px 0 0;
            box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
        }

        input[type="text"] {
            width: 90%;
            padding: 1rex 1rex;
            margin-right: 10px;
            font-size: 1rex;
            border-radius: 25px;
            border: 2px solid #ccc;
            outline: none;
            transition: border 0.3s;
        }

        input[type="text"]:focus {
            border-color: #00e2ff;
        }

        button {
            width:  3rex;
            height: 3rex;
            background-color: #4CAF50;
            border: none;
            color: white;
            font-size: 1rex;
            border-radius: 50%;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
            box-shadow: 0 4px 12px rgba(145, 208, 222, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: "仿宋";
        }

        button:hover {
            background-color: #45a049;
            transform: scale(1.1);
        }

        button:active {
            background-color: #388e3c;
        }

        .send-icon {
            width: 28px;
            height: 28px;
            fill: white;
        }

        img.avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
        }

        /* 悬浮显示的提示样式 */
        .tooltip {
            position: absolute;
            max-width: 100vw; 
            max-height: 100vw;
            padding: 5px 10px;
            background-color: rgba(0, 0, 0, 0.75);
            color: white;
            border-radius: 4px;
            font-size: 14px;
            pointer-events: none;
            visibility: hidden;  
            z-index: 1000;
            word-wrap: break-word; /* 防止长单词溢出 */
            white-space: normal; /* 正常换行 */
            text-overflow: ellipsis; /* 超出部分使用省略号 */
        }
        .source-link {
            color: blue;
            /* cursor: pointer; */
        }

        /* 点击后的紫色 */
        .clicked {
            color: purple;
        }
        span {
            display: inline-block;  /* 或者 display: block; */
            box-sizing: border-box;
            transition: transform 0.3s ease;
        }
        span:hover {
            transform: scale(1.1);  /* 增大元素但不影响布局 */
        }
        .snippet {
            display: block; /* 强制摘要换行 */
            overflow: hidden;
            text-overflow: ellipsis; /* 如果摘要内容过长，显示省略号 */
            white-space: nowrap; /* 防止文本换行 */
            max-width: 100%; /* 确保摘要不会超出容器宽度 */
        }

    </style>
</head>
<body>

<div class="header">
    AI智搜
</div>

<div class="container">
    <div id="chat-box" class="chat-box"></div>
</div>

<div class="input-container">
    <input type="text" id="user-input" placeholder="请输入问题..." autofocus>
    <button onclick="sendMessage()">
        <!-- <svg class="send-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <path d="M21 2L2 11l4 1.6L7 19l2.4-5.4L18 9l-1.4-4.8L21 2z"/>
        </svg> -->
        发送
    </button>
</div>
<div id="tooltip" class="tooltip"></div> <!-- 用于显示悬浮提示 -->

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<script>
    const apiUrl = "https://api.pearktrue.cn/api/aisearch/"; 
    let sources =[];
    // 发送用户消息并获取回复
    async function sendMessage() {
        const userMessage = document.getElementById('user-input').value;
        if (userMessage.trim() === '') return;
    
        // 显示用户消息
        displayMessage(userMessage, 'user');
        document.getElementById('user-input').value = '';
        
        try {
            // 发送API请求
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword: userMessage }) 
            });
    
            const data = await response.json();
            const botResponse = data.data.text || "没有获取到有效回复";  
            sources = data.data.sources || "没有找到数据来源";  
            
            typeWriter(botResponse, 'bot',sources);
        } catch (error) {
            console.error('请求失败:', error);
            typeWriter("抱歉，发生错误，请稍后再试。", 'bot',sources);
        }
    }
    
    // 显示消息
    function displayMessage(message, sender) {
        const chatBox = document.getElementById('chat-box');
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('chat-message', sender);
    
        const avatar = document.createElement('img');
        avatar.src = sender === 'user' 
            ? 'https://c-ssl.duitang.com/uploads/blog/202205/30/20220530101905_a4f0d.jpg' 
            : 'https://tse3-mm.cn.bing.net/th/id/OIP-C.vj7PFgA47Mo0hC-lEkN4ogHaFv?rs=1&pid=ImgDetMain';
        avatar.alt = sender === 'user' ? '用户头像' : '机器人头像';
    
        const textDiv = document.createElement('div');
        textDiv.classList.add('message-text');
        textDiv.innerHTML = marked.parse(`<h2>${message}</h2>`); 
    
        messageDiv.appendChild(avatar);
        messageDiv.appendChild(textDiv);
        
        chatBox.style.display = "flex"; 
        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    }


    
    // 监听 Enter 键发送消息
    document.getElementById('user-input').addEventListener('keydown', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault(); 
            sendMessage();
        }
    });
    
    // 打字效果
    function typeWriter(text, sender,sources) {
        const chatBox = document.getElementById('chat-box');
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('chat-message', sender);
    
        const avatar = document.createElement('img');
        avatar.src = sender === 'user' 
            ? 'https://c-ssl.duitang.com/uploads/blog/202205/30/20220530101905_a4f0d.jpg' 
            : 'https://tse3-mm.cn.bing.net/th/id/OIP-C.vj7PFgA47Mo0hC-lEkN4ogHaFv?rs=1&pid=ImgDetMain';
        avatar.alt = sender === 'user' ? '用户头像' : '机器人头像';
    
        const textDiv = document.createElement('div');
        textDiv.classList.add('message-text');
        let markdownText = '';
        let i = 0;


        text = text.replace(/\[(\d+)\]/g, (match, number) => {
            let source = sources[number-1]; // 获取对应的 source 对象
            if (source) {
                return`<span class="source-link" data-index="${number-1}"  onclick="handleClick(event)" 
                onmouseover="handleMouseOver(event)" onmouseleave="handleMouseOut()"> ${match} </span>`;
            }
            // 如果没有找到对应的链接，返回原始的 match
            return match;
        });
        // 使用 setInterval 打字效果
    const interval = setInterval(() => {
        markdownText += text.slice(i, i + 30); 
        textDiv.innerHTML = marked.parse(markdownText); 
        i+=30;
        if (i >= text.length) {
            clearInterval(interval);
        }
    }, 100); 
    
        messageDiv.appendChild(avatar);
        messageDiv.appendChild(textDiv);
        
        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    
    }

            // 点击事件处理
        function handleClick(event) {
            event.preventDefault();  
            const span = event.target; 
            let index = span.getAttribute('data-index'); 
            let url = sources[index].link; 
            let title = sources[index].title;
            console.log(`跳转到: ${title} (${url})`); 
            window.open(url, '_blank');
        }

        let isMouseInside = false; // 标记鼠标是否在元素内

        // 鼠标移入事件
        function handleMouseOver(event) {
            if (!isMouseInside) {
                isMouseInside = true;
                const contentDisplay = document.getElementById('tooltip');
                tooltip.style.visibility = 'visible';
                tooltip.style.left = `${event.pageX + 10}px`;  // 设置提示的 X 位置
                tooltip.style.top = `${event.pageY + 10}px`;   // 设置提示的 Y 位置

                let span = event.target;

                let index = span.getAttribute('data-index'); 
                let url = sources[index].link;  
                let title = sources[index].title;
                let snippet = sources[index].snippet; 

                if (url) {
                    contentDisplay.innerHTML = `
                        <strong>标题:</strong> <a href="${url}" target="_blank">${title}</a><br>
                        <strong>摘要:</strong> ${snippet}
                    `;
                } else {
                    contentDisplay.innerHTML = '没有找到对应的内容。';
                }
            }
        }

        // 鼠标移出事件
        function handleMouseOut() {
            if (isMouseInside) {
                isMouseInside = false;
                const tooltip = document.getElementById('tooltip');
                tooltip.style.visibility = 'hidden';
            }
        }
    </script>
    

</body>
</html>
